<template>
  <div class="app-container">
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="demo-form-inline"
      v-hasPermi="['sa:visit:query']"
    >
      <el-form-item label="拜访类型" prop="type">
        <el-select
          v-model="queryParams.type"
          filterable
          clearable
          size="small"
          placeholder="请选择拜访类型"
          style="width: 200px;"
        >
          <el-option
            v-for="item in contactTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="省份"
        prop="province"
      >
        <el-select v-model="queryParams.province" clearable filterable placeholder="请选择省份" style="width: 100%;">
          <el-option
            v-for="item in provinceList"
            :key="item.code"
            :label="item.name"
            :value="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model.trim="queryParams.projectName" :maxlength="50" size="small" placeholder="请输入项目名称"/>
      </el-form-item>
      <el-form-item label="客户/代理商" prop="schoolOrCompanyName">
        <el-input v-model.trim="queryParams.schoolOrCompanyName" :maxlength="50" size="small"
                  placeholder="请输入客户/代理商"/>
      </el-form-item>
      <el-form-item label="二级部门" prop="facultyName">
        <el-input v-model.trim="queryParams.facultyName" :maxlength="50" size="small" placeholder="请输入二级部门"/>
      </el-form-item>
      <el-form-item label="创建人" prop="createBy"
        label-width="68px"
      >
        <el-input v-model.trim="queryParams.createBy" :maxlength="15" size="small" placeholder="请输入创建人"/>
      </el-form-item>
      <el-form-item label="拜访日期" prop="visitDate">
        <el-date-picker
          v-model="visitDate"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="searchHandler">查询</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetHandler">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <el-col :span="12">
        <div class="grid-content bg-purple">
          <el-button plain type="primary" icon="el-icon-plus" size="mini" v-hasPermi="['sa:visit:add']" @click="openDialog(null)">增加</el-button>
<!--          <el-button plain type="warning" icon="el-icon-download" size="mini" v-hasPermi="['sa:visit:export']" @click="exportHandler">导出</el-button>-->
        </div>
      </el-col>
      <el-col :span="12">
        <div class="grid-content bg-purple"></div>
      </el-col>
    </el-row>

    <el-table
      ref="tableRef"
      :data="tableData"
      v-loading="loading"
      max-height="600"
      v-horizontal-scroll="'auto'"
      style="width: 100%;margin-top: 10px;">
      <el-table-column
        type="index"
        width="50"
        align="center"
        label="序号"
      >
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column
        property="visitDate"
        label="拜访日期"
        align="center"
        width="100"
      />
      <el-table-column
        property="type"
        label="拜访类型"
        align="center"
        width="80"
      >
        <template slot-scope="scope">
          <span>{{ getListValue(scope.row.type, contactTypeList) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        property="province"
        label="省份"
        align="center"
        width="80"
      />
      <el-table-column
        property="schoolOrCompanyName"
        label="名称"
        align="center"
        width="120"
      />
      <el-table-column
        property="facultyName"
        label="二级部门"
        align="center"
        width="100"
      />
      <el-table-column
        property="contactName"
        label="联系人"
        align="center"
        width="100"
      />
      <el-table-column
        property="job"
        label="职务"
        align="center"
        width="80"
      />
      <el-table-column
        property="phone"
        label="联系电话"
        align="center"
        width="120"
      />
      <el-table-column
        property="content"
        label="汇报内容"
        align="center"
        width="300"
      />
      <el-table-column
        property="intention"
        label="合作意向"
        align="center"
        width="80"
      />
      <el-table-column
        property="projectName"
        label="项目名称"
        align="center"
        width="120"
      />
      <el-table-column
        property="remark"
        label="备注"
        align="center"
      />
      <el-table-column
        property="createBy"
        label="创建人"
        align="center"
        width="100"
      />
      <el-table-column
        property="createTime"
        label="创建时间"
        align="center"
        width="160"
        sortable
      />
      <el-table-column
        label="操作"
        align="center"
        v-if="$auth.hasPermi('sa:visit:edit') || $auth.hasPermi('sa:visit:remove')"
      >
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" v-hasPermi="['sa:visit:edit']" @click="openDialog(scope.row)">修改</el-button>
          <el-popconfirm
            confirm-button-text="是"
            cancel-button-text="否"
            title="确定删除吗？"
            @confirm="deleteHandler(scope.row)"
          >
            <el-button slot="reference" icon="el-icon-delete" v-hasPermi="['sa:visit:remove']" type="text" style="margin-left: 10px">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="dialogTitle === 1 ? '新增' : '修改'"
      :visible.sync="dialogVisible"
      width="700px"
      close-on-click-modal
      :fullscreen="device === 'mobile'"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="demo-form" :label-position="device === 'mobile' ? 'top' : 'right'">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="拜访类型" prop="type">
              <el-radio-group v-model="form.type" style="width: 100%;" @change="contactTypeChange">
                <el-radio
                  v-for="item in contactTypeList"
                  :key="item.value"
                  :label="item.value">{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拜访日期" prop="visitDate">
              <el-date-picker
                v-model="form.visitDate"
                type="date"
                placeholder="选择拜访日期"
                value-format="yyyy-MM-dd"
                style="width: 100%;"
                :picker-options="pickerOptions"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 填写客户名称和供应商名称 -->
        <el-row :gutter="20" v-if="form.type === 0">
          <el-col :span="12">
            <el-form-item
              label="名称"
              prop="schoolOrCompanyName"
              :rules="[
                { required: true, message: '请选择客户', trigger: 'blur' },
              ]"
            >
              <el-select
                v-model="form.schoolOrCompanyName"
                filterable
                clearable
                default-first-option
                placeholder="请选择客户"
                style="width: 100%"
                @change="changeCustomerHandler"
              >
                <el-option
                  v-for="item in customerList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="省份"
              prop="province"
              :rules="[
                {required: !(form.id != null || !isCreateAgent), message: '请选择省份', trigger: 'blur'}
              ]"
            >
              <el-select v-model="form.province" :disabled="form.id != null || !isCreateAgent" clearable filterable placeholder="请选择省份" style="width: 100%;">
                <el-option
                  v-for="item in provinceList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="form.type === 1">
          <el-col :span="12">
            <el-form-item
              label="名称"
              prop="schoolOrCompanyName"
              :rules="[
                { required: true, message: '请选择代理商', trigger: 'change' },
              ]"
              v-if="form.type === 1"
            >
              <el-select
                v-model="form.schoolOrCompanyName"
                filterable
                clearable
                default-first-option
                placeholder="请选择代理商"
                style="width: 100%"
                @change="changeCustomerHandler"
              >
                <el-option
                  v-for="item in agentList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="省份"
              prop="province"
              :rules="[
                {required: !(form.id != null || !isCreateAgent), message: '请选择省份', trigger: 'blur'}
              ]"
            >
              <el-select v-model="form.province" :disabled="form.id != null || !isCreateAgent" clearable filterable placeholder="请选择省份" style="width: 100%;">
                <el-option
                  v-for="item in provinceList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="form.type === 0">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectFundId">
              <el-select
                v-model="form.projectFundId"
                filterable
                clearable
                placeholder="请选择项目"
                style="width: 100%;"
                @change="changeProjectHandler"
              >
                <el-option
                  v-for="item in projectList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="二级部门"
              prop="facultyName"
              :rules="[
                { required: true, message: '请选择二级部门', trigger: 'change' },
              ]"
            >
              <el-select
                v-model="form.facultyName"
                filterable
                clearable
                default-first-option
                placeholder="请选择二级部门"
                style="width: 100%"
                v-if="!(form.id == null && isCreateCustomer)"
                @change="changeSchoolHandler"
              >
                <el-option
                  v-for="item in schoolList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select>
              <!-- 如果是手动创建的客户 -->
              <el-input v-else v-model.trim="form.facultyName" placeholder="请输入二级部门"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="this.form.type === 0">
          <el-col :span="12">
            <el-form-item label="客户属性" :prop="!(form.id == null && isCreateCustomer) ? '' : 'clientIsImportant'">
              <el-select
                v-model="form.clientIsImportant"
                filterable
                clearable
                :disabled="!(form.id == null && isCreateCustomer)"
                placeholder="请选择属性" style="width: 100%;"
                @change="changePropertyHandler"
              >
                <el-option
                  v-for="item in isCustomerList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="依据" :prop="!(form.id == null && isCreateCustomer) ? '' : 'clientBasis'" v-if="form.clientIsImportant === 1">
              <el-select
                v-model="form.clientBasis"
                filterable
                clearable
                multiple
                :disabled="!(form.id == null && isCreateCustomer)"
                placeholder="请选择重点客户依据" style="width: 100%;"
              >
                <el-option
                  v-for="item in dict.type.sys_key_customer_basis"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-select
                v-model="form.contactId"
                filterable
                clearable
                default-first-option
                placeholder="请选择联系人"
                style="width: 100%"
                v-if="!(form.id == null && isCreateCustomer)"
                @change="changeContactHandler"
              >
                <el-option
                  v-for="item in contactList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
              <!-- 如果是手动创建的客户 -->
              <el-input v-else v-model.trim="form.contactName" placeholder="请输入联系人"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务" :prop="!(form.id == null && isCreateCustomer) ? '' : 'job'">
              <el-input v-model.trim="form.job" :disabled="!(form.id == null && isCreateCustomer)" :maxlength="15" placeholder="请输入职务"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model.trim="form.phone" :maxlength="15" placeholder="请输入手机号码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合作意向" prop="intention">
<!--              <el-input v-model.trim="form.intention" :maxlength="100" placeholder="请输入合作意向"></el-input>-->
              <el-select v-model="form.intention" clearable placeholder="请选择合作意向" style="width: 100%;">
                <el-option
                  v-for="item in dict.type.sys_cooperate_intention"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人属性" :prop="!(form.id == null && isCreateCustomer) ? '' : 'contactIsImportant'" v-if="this.form.type === 0">
              <el-select
                v-model="form.contactIsImportant"
                filterable
                clearable
                :disabled="!(form.id == null && isCreateCustomer)"
                placeholder="请选择联系人属性"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in isImportantList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="重点依据"
              :prop="!(form.id == null && isCreateCustomer) ? '' : 'contactBasis'"
              v-if="this.form.type === 0 && this.form.contactIsImportant === 1"
            >
              <el-select v-model="form.contactBasis" :disabled="!(form.id == null && isCreateCustomer)" clearable filterable placeholder="请选择依据" style="width: 100%;">
                <el-option
                  v-for="item in dict.type.sys_key_contact_basis"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="汇报内容" prop="content">
          <el-input
            v-model.trim="form.content"
            type="textarea"
            :maxlength="500"
            placeholder="请输入汇报内容"
            :autosize="{ minRows: 2 }"
          ></el-input>
          <div>
            <el-checkbox v-model="form.activityId" v-if="form.type === 1" :false-label="0" :true-label="3">
              协助代理商处理商务事宜
            </el-checkbox>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" type="textarea" :maxlength="200" placeholder="请输入备注" :autosize="{ minRows: 2 }"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {addDataApi, deleteDataApi, getDataListApi, updateDataApi} from "@/api/crm/sa/visit";
import {getDataListApi as getAllCustomerListApi} from "@/api/crm/md/customer";
import {getDataListApi as getAllSchoolListApi} from "@/api/crm/md/school";
import {getDataListApi as getAllContactListApi} from "@/api/crm/md/contacts";
import {getDataListApi as getAllAgentListApi} from "@/api/crm/md/agent";
import {addDataApi as addActivityDataApi} from "@/api/crm/md/activity";
import { getDataListApi as getAllProjectListApi } from "@/api/crm/md/project"
import ProvinceData from '@/views/crm/data/province.json'
import {getUserProfile} from "@/api/system/user";
import { mapGetters } from 'vuex';
import { validatePhoneNumber } from "@/utils/validate";

export default {
  name: 'VisitView',
  dicts: ['sys_key_contact_basis', 'sys_key_customer_basis', 'sys_activity_type', 'sys_cooperate_intention'],
  data() {
    const checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入手机号码'));
      }

      if (!validatePhoneNumber(value)) {
        callback(new Error('请输入正确的手机号码'));
      } else {
        callback();
      }
    };

    return {
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      // 加载动画
      loading: true,
      // 是否自定义客户
      isCreateCustomer: false,
      // 是否自定义代理商
      isCreateAgent: false,
      // 是否自定义联系人
      isCreateContact: false,
      pickerOptions: {
        disabledDate(time) {
          // 禁止选择今天及今天之后的日期
          return time.getTime() > Date.now();
        }
      },
      // 拜访日期
      visitDate: [],
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 拜访类型
      contactTypeList: [
        {
          value: 0,
          label: '客户'
        },
        {
          value: 1,
          label: '代理商'
        }
      ],
      // 新增和修改参数
      form: {
        clientIsImportant: 0, // 重点客户
        contactIsImportant: 0,
        contactBasis: null,
        createBy: "", // 用户 *
        createTime: "", // 创建时间 *
        id: null, // id
        intention: "", // 合作意向
        province: "", // 省份 *
        remark: "", // 备注
        updateBy: "", // 更新人
        updateTime: "", // 更新时间
        contactId: null, // 联系人id
        contactName: "", // 联系人姓名
        content: "", // 汇报内容
        facultyName: "", // 二级部门名字
        activityId: 0, // 参与活动类型value
        job: "", // 职务
        phone: "", // 联系人手机号
        projectFundId: null, // 项目id
        projectName: "", // 项目名称
        schoolOrCompanyName: null, // 学校/代理商名称
        type: 0, // 类型 0客户 1代理商
        visitDate: "", // 拜访日期
        clientBasis: [], // 重点客户的依据
      },
      // 重点联系人下拉数据
      isImportantList: [
        {
          value: 0,
          label: '普通联系人'
        },
        {
          value: 1,
          label: '重点联系人'
        }
      ],
      // 重点客户下拉数据
      isCustomerList: [
        {
          value: 0,
          label: '普通客户'
        },
        {
          value: 1,
          label: '重点客户'
        }
      ],
      // 表单的校验规则
      rules: {
        visitDate: [
          {required: true, message: '请选择拜访日期', trigger: 'change'}
        ],
        name: [
          {required: true, message: '请填写代理商名称', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '请选择客户/代理商', trigger: 'change'}
        ],
        clientIsImportant: [
          {required: true, message: '请选择属性', trigger: 'change'}
        ],
        contactIsImportant: [
          {required: true, message: '请选择联系人属性', trigger: 'change'}
        ],
        contactBasis: [
          {required: true, message: '请选择重点联系人依据', trigger: 'change'}
        ],
        clientBasis: [
          {required: true, message: '请选择重点客户依据', trigger: 'change'}
        ],
        contactName: [
          {required: true, message: '请选择联系人', trigger: 'change'}
        ],
        job: [
          {required: true, message: '请填写职务', trigger: 'blur'}
        ],
        phone: [
          { required: true, validator: checkPhone, trigger: 'blur' }
        ],
        // intention: [
        //   {required: true, message: '请选择合作意向', trigger: 'change'}
        // ],
        content: [
          {required: true, message: '请填写汇报内容', trigger: 'blur'}
        ],
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        province: "", // 省份
        projectName: "", // 项目名称 *
        schoolOrCompanyName: null, // 学校/代理商名称
        type: null, // 拜访类型
        createBy: '', // 用户
        facultyName: '', // 二级部门名字
        startDate: '', // 开始时间
        endDate: '', // 结束时间
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
      // 客户数据
      customerList: [],
      // 二级部门数据
      schoolList: [],
      // 联系人数据
      contactList: [],
      // 代理商数据
      agentList: [],
      // 项目数据
      projectList: [],
    }
  },
  computed: {
    ...mapGetters([
      'device'
    ]),
  },
  watch: {
    visitDate: {
      handler(newV) {
        if (newV) {
          this.queryParams.startDate = newV[0] ?? ''
          this.queryParams.endDate = newV[1] ?? ''
        } else {
          this.queryParams.startDate = ''
          this.queryParams.endDate = ''
        }
      },
    },
    'form.contactIsImportant': {
      handler(newV) {
        if (newV !== 1) {
          this.form.contactBasis = null
        }
      }
    },
  },
  created() {
    this.provinceList = ProvinceData
    this.getList()
    this.getUserinfo()
    this.getAllCustomerList()
    this.getAllAgentList()
  },
  activated() {
    this.getList()
  },
  methods: {
    contactTypeChange() {
      // 清除客户信息
      this.form.schoolOrCompanyName = null
      this.form.province = ""
      // 清除项目信息
      this.form.projectFundId = null
      this.projectList.length = 0
      // 清除二级部门信息
      this.schoolList.length = 0
      this.form.facultyName = null
      // 清除联系人信息
      this.cleanContectInfo()
      this.contactList.length = 0
      this.$nextTick(()=>{
        this.$refs.formRef.clearValidate();
      })
    },
    // 修改项目的回调
    async changeProjectHandler(val) {
      const result = this.isTrueDate(val, 'id', this.projectList)

      if(result && result.id) {
        this.form.schoolOrCompanyName = result.clientName
        await this.changeCustomerHandler(result.clientName)
        this.form.facultyName = result.facultyName
        await this.changeSchoolHandler(result.facultyName)
        this.form.contactName = result.contactName
        this.form.contactId = result.contactId
        this.changeContactHandler(result.contactId)
      }
    },
    // 查询全部项目
    getAllProjectList(clientName) {
      getAllProjectListApi({ clientName }).then((res) => {
        this.projectList = res.data?.list?.rows ?? []
      })
    },
    // 选择重点的回调
    changePropertyHandler(val) {
      if (val === 0) {
        this.form.clientBasis = []
      }
    },
    // 是否参与活动事宜
    changeActivityIdHandler(val) {
      if (!this.form.visitDate) {
        this.$notify.warning('请选择拜访日期')
        this.form.activityId = 0
        return false
      }

      if (val) {
        addActivityDataApi({
          type: val,
          province: this.form.province,
          activityDate: this.form.visitDate,
          createBy: this.user.userName,
          updateBy: this.user.userName,
          content: this.form.content,
          remark: this.form.remark,
        })
          .then(() => {
          })
          .catch(() => {
          })
      }
    },
    // 获取全部代理商数据
    getAllAgentList() {
      getAllAgentListApi().then((res) => {
        this.agentList = res?.rows ?? []
      })
    },
    // 改变联系人的回调
    // 根据联系人姓名 在联系人信息表中查询 找到职务、手机号
    changeContactHandler(id) {
      let result = null
      this.contactList.map((item) => {
        if (item.id === id) result = {...item}
      })

      if (result) {
        this.isCreateContact = false
        this.form.job = result.job
        this.form.phone = result.phone
        this.form.contactIsImportant = result.isImportant ?? 0
        this.form.contactBasis = result.basis ?? null
        this.form.contactName = result.name
      } else {
        this.isCreateContact = true
        // this.form.contactId = ""
        this.form.contactName = id
      }
    },
    // 改变二级部门的回调
    async changeSchoolHandler(val) {
      // if (!flag) {
        this.cleanContectInfo()
      // }
      if(!val) return false

      await this.getAllContactList(val)
    },
    // 获取全部联系人信息
    async getAllContactList(val) {

      if(!val) return false

      let flag = { id: null }

      if(this.form.type === 0) { // 选择客户的时候查院系
        flag = this.isTrueDate(val, 'name', this.schoolList)
      } else { // 选择代理商查代理商
        flag = this.isTrueDate(val, 'name', this.agentList)
      }


      if(!flag.id) return false

      const payload = {
        clientAgentId: flag.id
      }
      payload.type = this.form.type
      // if (this.form.type === 0) { // 选择客户的时候
      //   payload.faculty = val
      // } else { // 选择代理商的时候
      //   // payload.clientAgentId = val
      //   payload.schoolOrCompanyName = val
      // }
      const res = await getAllContactListApi(payload)
      this.contactList = res.rows ?? []
    },
    // 遍历list中的属性per是否与value相同
    isTrue(value = "", per = "", list = []) {
      return list.some((item) => {
        return item[per].localeCompare(value) === 0
      })
    },
    // 清空联系人相关信息
    cleanContectInfo() {
      this.form.contactName = ""
      this.form.job= ""
      this.form.phone = ""
      this.form.intention = ""
      this.form.content = ""
      this.form.contactId = ""
      this.form.contactIsImportant = 0
      this.form.clientIsImportant = 0
    },
    // 改变客户的回调
    async changeCustomerHandler(val) {
      if (this.form.type === 1) { // 选择代理商的时候
        // 如果代理商list不存在当前条目
        // 说明是用户自定义创建的
        // 需要清掉部门和联系人信息
        const flag = this.isTrue(val, 'name', this.agentList)

        if (!flag) {
          this.isCreateAgent = true
          this.form.facultyName = ""
          this.cleanContectInfo()
        } else if (this.form.schoolOrCompanyName !== val) {
          this.isCreateAgent = false
          const result = this.isTrueDate(val, 'name', this.agentList)
          this.form.clientIsImportant = result.isImportant ?? 0
          this.form.clientBasis = (result.basis ?? "").split(',').filter(i => i) ?? []
          this.form.province = result.province
          this.form.contactId = null
          this.form.facultyName = ""
          this.form.phone = ""
          this.contactList.length = 0
        } else {
          this.isCreateAgent = false
          const result = this.isTrueDate(val, 'name', this.agentList)
          this.form.clientIsImportant = result.isImportant ?? 0
          this.form.clientBasis = (result.basis ?? "").split(',').filter(i => i) ?? []
          this.form.province = result.province
        }
        // let id = null
        // this.agentList.map((item) => {
        //   if (item.name.localeCompare(val) === 0) id = item.id
        // })
        // id &&
        await this.getAllContactList(val)
      } else if (this.form.type === 0) { // 选择客户的时候
        // 如果客户list不存在当前条目
        // 说明是用户自定义创建的
        // 需要清掉二级部门和联系人信息
        const flag = this.isTrue(val, 'name', this.customerList)
        if (!flag) {
          this.isCreateAgent = true
          this.isCreateCustomer = true
          this.form.facultyName = ""
          this.form.projectFundId = null
          this.projectList.length = 0
          this.contactList.length = 0
          this.schoolList.length = 0
          this.cleanContectInfo()
        } else if (this.form.schoolOrCompanyName !== val) {
          this.isCreateAgent = false
          this.isCreateCustomer = false
          const result = this.isTrueDate(val, 'name', this.customerList)
          this.form.clientIsImportant = result.isImportant ?? 0
          this.form.clientBasis = (result.basis ?? "").split(',').filter(i => i) ?? []
          this.form.province = result.province
          this.form.contactId = null
          this.form.facultyName = ""
          this.form.phone = ""
          this.contactList.length = 0
          this.getAllProjectList(result.name)
          await this.getAllSchoolList(val)
        } else {
          this.isCreateAgent = false
          this.isCreateCustomer = false
          const result = this.isTrueDate(val, 'name', this.customerList)
          this.form.clientIsImportant = result.isImportant ?? 0
          this.form.clientBasis = (result.basis ?? "").split(',').filter(i => i) ?? []
          this.form.province = result.province
          this.getAllProjectList(result.name)
          await this.getAllSchoolList(val)
        }
      }
    },
    // 遍历list中的属性per是否与value相同，返回相同的数据项
    isTrueDate(value = "", per = "", list = []) {
      let result = {}
      list.map((item) => {
        if(typeof item[per] === 'number') {
          if(item[per] === value) {
            result = item
          }
        }else {
          if(item[per].localeCompare(value) === 0) {
            result = item
          }
        }
      })

      return result
    },
    // 获取全部二级部门信息
    async getAllSchoolList(clientName) {
      const res = await getAllSchoolListApi({clientName})
      this.schoolList = res.rows ?? []
    },
    // 获取全部客户信息
    getAllCustomerList() {
      getAllCustomerListApi().then((res) => {
        this.customerList = (res.rows ?? []).filter(i => i.clientType !== '博诺集团')
      })
    },
    // 获取根据list中的value返回label
    getListValue(data, list, value = 'value') {
      let label = ''
      list.map((item) => {
        if (+item[value] === +data) {
          label = item.label
        }
      })
      return label
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList() {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if (res.code === 200) {
        this.tableData = res.rows
        this.total = res.total
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 获取学校信息
    async getSchoolInfo() {
      await this.changeCustomerHandler(this.form.schoolOrCompanyName)
      await this.getAllContactList(this.form.facultyName)
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.formId = row.id
        this.form = {
          ...row,
          clientBasis: (row.clientBasis?.split(',') ?? []).filter(i => i)
        }
        this.dialogTitle = 2
        // 获取学校信息
        this.getSchoolInfo()
      } else { // 新增拜访记录，需要清掉二级部门和联系人下拉框数据
        if(this.formId) {
          this.form = { ...this.$options.data().form }
          // 客户数据
          // this.customerList = []
          // 二级部门数据
          this.schoolList.length = 0
          // 联系人数据
          this.contactList.length = 0
          // 代理商数据
          // this.agentList = []
        }

        this.formId = null
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      this.$nextTick(()=>{
        this.$refs['formRef'].clearValidate();
        // this.resetForm('formRef')
      })
    },
    // 导出的回调
    async exportHandler() {
      this.download('crm/visit/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `visitRecords_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.clientBasis = (this.form.clientBasis ?? [])?.join(',') ?? ""
          if (this.dialogTitle === 1) {
            this.changeActivityIdHandler(this.form.activityId)
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
          this.getAllCustomerList()
          this.getAllAgentList()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
        userId: this.user.userId,
        contactIsImportant: this.form.type === 0 ? this.form.contactIsImportant : 0,
        contactBasis: this.form.type === 0 ? this.form.contactBasis : null,
      }
      const res = await addDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
        // 是否自定义客户
        this.isCreateCustomer = false
        // 是否自定义代理商
        this.isCreateAgent = false
        // 是否自定义联系人
        this.isCreateContact = false
        this.$refs.formRef.resetFields()
        this.cleanContectInfo()
        this.formId = -1
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
        contactIsImportant: this.form.type === 0 ? this.form.contactIsImportant : 0,
        contactBasis: this.form.type === 0 ? this.form.contactBasis : null,
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
        // 是否自定义客户
        this.isCreateCustomer = false
        // 是否自定义代理商
        this.isCreateAgent = false
        // 是否自定义联系人
        this.isCreateContact = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.visitDate = []
      this.resetForm('queryFormRef')
    },
  },
}
</script>
<style scoped lang="scss">

</style>
